package mundo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

public class ThreadComunicacion extends Thread {

	/*TODO Cambiar el portName segun corresponda*/
	private static final String PORT_NAME = "/dev/cu.usbmodem641";
	/** Milliseconds to block while waiting for port open */
	private static final int TIME_OUT = 2000;
	/** Default bits per second for COM port. */
	private static final int DATA_RATE = 9600;

	/** The streams to the port, and the port */
	private InputStream input;
	private OutputStream output;
	private SerialPort serialPort;

	private int numeroAEnviar;
	private boolean escribir;
	private Control mainControl;
	private boolean continuar;
	public ThreadComunicacion(Control control)
	{
		mainControl=control;
		numeroAEnviar=0;
		initializeArduinoConnection();
	}

	@SuppressWarnings("rawtypes")
	public void initializeArduinoConnection(){

		escribir=false;
		continuar=true;

		CommPortIdentifier portId = null;
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		// iterate through, looking for the port
		while (portEnum.hasMoreElements()) 
		{
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();

			if (PORT_NAME.equals(currPortId.getName())) {
				portId = currPortId;
				break;
			}
		}

		if (portId != null) 
		{

			try {
				// open serial port, and use class name for the appName.
				serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);

				// set port parameters
				serialPort.setSerialPortParams(DATA_RATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

				// open the streams
				output = serialPort.getOutputStream();

				input = serialPort.getInputStream();

			} catch (Exception e) {e.printStackTrace();}
		}
		else System.out.println("Could not find Comunication port.");
	}

	public void setNumeroAEnviar(int numeroAEnviar) {
		this.numeroAEnviar = numeroAEnviar;
		escribir = true;
	}

	public void run()
	{
		while(continuar){
			try 
			{
				if(input.available()>0)
				{
					int entrada = input.read();
					mainControl.regularPasoDeAgua(entrada);
				} 
				if(escribir){
					char mensaje = (char) (numeroAEnviar+65);
					output.write(mensaje);
					//System.out.println("Lts >>:"+numeroAEnviar);
					escribir=false;
				}
			}	
			catch (IOException e) {e.printStackTrace();}
		}
	}

}